<template>
  <a-form v-if="enable" id="formForgetPassword" ref="formForgetPassword" :form="form">
    <a-popover placement="rightTop" trigger="click" :visible="state.passwordLevelChecked">
      <template slot="content">
        <div :style="{ width: '240px' }">
          <div :class="['user-register', passwordLevelClass]">强度：<span>{{ passwordLevelName }}</span></div>
          <a-progress :percent="state.percent" :show-info="false" :stroke-color=" passwordLevelColor " />
          <div style="margin-top: 10px;">
            <span>请至少输入 6 个字符。请不要使用容易被猜到的密码。</span>
          </div>
        </div>
      </template>
      <a-form-item label="输入密码">
        <a-input
          v-decorator="['password', {rules: [{ required: true, message: '6~18位密码，区分大小写'}, { validator: this.handlePasswordLevel }], validateTrigger: ['change', 'blur']}]"
          size="large"
          type="password"
          autocomplete="false"
          placeholder="6~18位密码，区分大小写"
          @click="handlePasswordInputClick"
        />
      </a-form-item>
    </a-popover>

    <a-form-item label="确认密码">
      <a-input
        v-decorator="['password2', {rules: [{ required: true, message: '6~18位密码，区分大小写' }, { validator: this.handlePasswordCheck }], validateTrigger: ['change', 'blur']}]"
        size="large"
        type="password"
        autocomplete="false"
        placeholder="确认密码"
      />
    </a-form-item>

    <a-form-item>
      <nuxt-link v-if="isSet" class="login" to="/system/Account" style="float:right">返回</nuxt-link>
      <nuxt-link v-else class="login" to="/users/login/" style="float:right">返回登录页面</nuxt-link>
      <a-button
        size="large"
        class="primary-btn register-button"
        html-type="submit"
        :loading="registerBtn"
        :disabled="registerBtn"
        @click.stop.prevent="handleSubmit"
      >重置密码
      </a-button>

    </a-form-item>
    <div v-if="!enable">{{ error }}</div>
  </a-form>
</template>

<script>
import { mixinDevice } from '@/utils/mixin.js'
import { getUrlKey } from '@/utils/util.js'

const levelNames = {
  0: '低',
  1: '低',
  2: '中',
  3: '强'
}
const levelClass = {
  0: 'error',
  1: 'error',
  2: 'warning',
  3: 'success'
}
const levelColor = {
  0: '#ff0000',
  1: '#ff0000',
  2: '#ff7e05',
  3: '#52c41a'
}
export default {
  name: 'ResetPasswordCode',
  auth: false,
  layout: 'login-layout',
  mixins: [mixinDevice],
  data () {
    return {
      form: process.client ? this.$form.createForm(this) : null,
      enable: false,
      error: '',
      acode: '',
      username: '',
      state: {
        passwordLevel: 0,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000'
      },
      registerBtn: false,

      isSet: false
    }
  },
  computed: {
    passwordLevelClass () {
      return levelClass[this.state.passwordLevel]
    },
    passwordLevelName () {
      return levelNames[this.state.passwordLevel]
    },
    passwordLevelColor () {
      return levelColor[this.state.passwordLevel]
    }
  },
  watch: {
    $route: {
      handler (t, f) {
        const isEnter = /(System-SetPassword|users-ResetPassword)/.test(t.name)
        this.enable = false
        this.isSet = false

        if (isEnter && t.params && t.params.mobile && t.params.captcha) {
          this.enable = true
          if (t.name === 'System-SetPassword') this.isSet = true
        } else if (isEnter) {
          this.$router.replace(`${t.name === 'System-SetPassword' ? '/system/Verification' : '/users/ForgotPassword'}`)
        }
      },
      immediate: true
    }
  },
  mounted () {
    const acode = process.client ? getUrlKey('acode') || this.$route.params.captcha : ''
    if (acode === '' || acode == null) {
      this.error = '没有激活码，请确认已经获取验证码'
    } else {
      this.enable = true
      this.acode = acode
      this.mobile = this.$route.params.mobile
    }
  },
  methods: {
    async resetPassword (params) {
      const res = await this.$authlessApi.resetPassword(params)
      return res
    },
    handlePasswordLevel (rule, value, callback) {
      let level = 0

      // 判断这个字符串中有没有数字
      if (/[0-9]/.test(value)) {
        level++
      }
      // 判断字符串中有没有字母
      if (/[a-zA-Z]/.test(value)) {
        level++
      }
      // 判断字符串中有没有特殊符号
      if (/[^0-9a-zA-Z_]/.test(value)) {
        level++
      }
      this.state.passwordLevel = level
      this.state.percent = level * 30
      if (level >= 2 && value.length > 5 && value.length < 19) {
        if (level >= 3) {
          this.state.percent = 100
        }
        callback()
      } else {
        if (level === 0) {
          this.state.percent = 10
        }
        let errorMsg = '密码强度不够'
        if (level >= 2) {
          if (value.length < 6) errorMsg = '请至少输入 6 个字符'
          else if (value.length > 18) errorMsg = '请不要超过 18 个字符'
        }
        callback(new Error(errorMsg))
      }
    },

    handlePasswordCheck (rule, value, callback) {
      const password = this.form.getFieldValue('password')
      if (value === undefined) {
        callback(new Error('请输入密码'))
      }
      if (value && password && value.trim() !== password.trim()) {
        callback(new Error('两次密码不一致'))
      }
      callback()
    },

    handlePasswordInputClick () {
      if (!this.isMobile()) {
        this.state.passwordLevelChecked = true
        return
      }
      this.state.passwordLevelChecked = false
    },

    handleSubmit () {
      const { form: { validateFields }} = this
      validateFields({ force: true }, (err, values) => {
        if (!err) {
          values.acode = this.acode
          values.mobile = this.mobile
          this.resetPassword({ ...values })
            .then((res) => {
              if (res.data.code === '020002' || res.data.code === '020000') {
                this.$notification.error({
                  message: res.data.mesg || res.data.data,
                  description: `请确认后重新输入`
                })
              } else {
                this.$router.push({ name: 'users-ResetResult', params: { ...values }})
              }
            }
            )
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
  .user-register {

    &.error {
      color: #ff0000;
    }

    &.warning {
      color: #ff7e05;
    }

    &.success {
      color: #52c41a;
    }

  }

  .user-layout-register {
    .ant-input-group-addon:first-child {
      background-color: #fff;
    }
  }
</style>
<style lang="less" scoped>
  .user-layout-register {

    & > h3 {
      font-size: 16px;
      margin-bottom: 20px;
    }

    .getCaptcha {
      display: block;
      width: 100%;
      height: 40px;
    }

    .register-button {
      width: 50%;
    }

    .login {
      float: right;
      line-height: 40px;
    }
  }
  .main{
    background-position: center;
    background-size: cover;
    position: absolute;
    top:0;
    left: 0;
    right: 0;
    bottom: 0;
    .form{
        padding:50px;
        position: absolute;
        top:50%;
        left:50%;
        transform: translate(-50%,-50%);
        background: #fff;
        width: 70%;
        border-radius: 10px;
        .logo{
          img{
            width: 40%;
            height: auto;
            margin-bottom: 30px;
          }
        }
        .lost-pwd{
          display: inline-block;
          color:#1890ff;
          cursor: pointer;
        }
        /deep/ .ant-btn{
          width: 40%;
          border-radius: 20px;
          padding:20px;
          line-height: 0;
          margin-top:30px;
        }
        .form-right{
          .small-bg{
            img{
              width: 80%;
              height: auto;
              margin-left: calc(10% + 10px);
              margin-top: -50px;
            }

          }
        }
    }
}
</style>
